// 格式化日期为 YYYY-MM-DD 格式
export const formatDate = (date) => {
  if (!date) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 判断两个日期是否相等
export const isDateEqual = (date1, date2) => {
  if (!date1 || !date2) return false;
  return formatDate(date1) === formatDate(date2);
};

// 判断日期1是否在日期2之前
export const isDateBefore = (date1, date2) => {
  if (!date1 || !date2) return false;
  return date1.getTime() < date2.getTime();
};

// 判断日期1是否在日期2之后
export const isDateAfter = (date1, date2) => {
  if (!date1 || !date2) return false;
  return date1.getTime() > date2.getTime();
};

// 生成某月的所有日期数据
export const generateMonthDays = (year, month) => {
  const days = [];
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const firstDayOfWeek = firstDay.getDay();

  // 添加上月剩余日期
  for (let i = 0; i < firstDayOfWeek; i++) {
    days.push(null);
  }

  // 添加当月日期
  for (let date = 1; date <= lastDay.getDate(); date++) {
    days.push({
      year,
      month: month + 1,
      date,
      isCurrentMonth: true,
    });
  }

  // 补充下月日期，使总数为 42（6周）
  const remainingDays = 42 - days.length;
  for (let i = 0; i < remainingDays; i++) {
    days.push(null);
  }

  return days;
};

// 获取相对日期
export const getRelativeDate = (date, offset) => {
  const newDate = new Date(date);
  newDate.setDate(date.getDate() + offset);
  return newDate;
};

// 获取月份的天数
export const getDaysInMonth = (year, month) => {
  return new Date(year, month + 1, 0).getDate();
};

// 判断是否是闰年
export const isLeapYear = (year) => {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};

// 获取两个日期之间的天数
export const getDaysBetween = (date1, date2) => {
  if (!date1 || !date2) return 0;
  const timeDiff = Math.abs(date2.getTime() - date1.getTime());
  return Math.ceil(timeDiff / (1000 * 3600 * 24));
};
